//
// Created by kongkong on 16/9/25.
// Copyright (c) 2016 Kongkong. All rights reserved.
//

#import "KKResponse.h"

@interface KKResponse ()

@property(nonatomic, strong) NSDictionary *originalData;

@property(nonatomic, assign) ServerReturnCode ret;
@property(nonatomic, strong) NSString *serverMessage;

@property(nonatomic, assign) int bizCode;
@property(nonatomic, strong) NSString *bizMsg;

@property(nonatomic, strong) id originResult;

@end

@implementation KKResponse

- (BOOL)isSuccess {

    return self.ret == RET_NORMAL &&
            self.bizCode == 0;
}

- (NSString *)errorMessage {

    if ([self isSuccess]) {
        return nil;
    }

    if (!EMPTY_STR(self.serverMessage)) {
        return [self.serverMessage stringByAppendingFormat:@"\tcode: %d", self.ret];
    }

    if (!EMPTY_STR(self.bizMsg)) {
        return [self.bizMsg stringByAppendingFormat:@"\terror: %d", self.bizCode];
    }

    return nil;
}

+ (id <KKResponseProtocol>)objectWithData:(NSDictionary *)data reflexClass:(Class)reflexClass {
    if (!data) {
        return nil;
    }

    KKResponse *response;
    response = [[KKResponse alloc] init];
    response.originalData = data;

    response.ret = (ServerReturnCode) [data[@"ret"] integerValue];
    response.serverMessage = data[@"msg"];

    id resultData = data[@"data"];
    if ([resultData isKindOfClass:[NSDictionary class]]){
        response.bizCode = [resultData[@"code"] intValue];
        response.bizMsg = resultData[@"msg"];
        response.originResult = resultData[@"result"];
        if (reflexClass){
            // TODO 反序列化
        }
    }

    return response;
}

- (void)showError{
    if ([self errorMessage]){
        [MBProgressHUD showError:[self errorMessage]];
    }
    else{
        [MBProgressHUD showError:@"操作异常，请稍候重试"];
    }
}

@end
